package com.originskyseed.platform.role.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.role.i18n.RoleResponseMsg;
import com.originskyseed.platform.role.model.Menu;
import com.originskyseed.platform.role.service.IMenuService;
import com.originskyseed.platform.role.service.IRoleRelMenuService;
import com.originskyseed.platform.role.service.IRoleService;
import com.originskyseed.platform.role.vo.request.MenuListRequestVO;
import com.originskyseed.platform.user.model.UserInfo;

/**
 * 菜单Controller类
 *
 * @author LiangMingHui
 *
 */
@Controller
@RequestMapping("/menu")
@BaseLocaleResource(localeFileName = "i18n_role")
public class MenuController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(MenuController.class);

	@DubboReference
	private IMenuService menuService;

	@DubboReference
	private IRoleRelMenuService roleRelMenuService;

	@DubboReference
	private IRoleService roleService;

	/**
	 * 菜单编辑页面
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/menuEdit.json")
	public BaseResponseBody menuEdit(HttpServletRequest request) {
		BaseResponseBody result = null;
		Map<String, Object> model = new HashMap<String, Object>();
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			String parentName = "";// 父菜单名称
			Menu menu = this.menuService.selectByPrimaryKey(id);
			model.put("menu", menu);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_LIST_SUCCESS.getMsg()), model);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 菜单选择页面
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/menuSelect.html")
	public ModelAndView menuSelect(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> model = new HashMap<String, Object>();
		try {

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return new ModelAndView("menu/menu_select", model);
	}

	/**
	 * 菜单绑定图标页面
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/menuBindIconList.html")
	public ModelAndView menuBindIconList(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> model = new HashMap<String, Object>();
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			model.put("id", id);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return new ModelAndView("menu/menu_bind_icon_list", model);
	}

	/**
	 * 菜单绑定角色
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/menuBindRole.json")
	@RequiredParams(names = { "permissionId" })
	public BaseResponseBody menuBindRole(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String permissionId = this.getParameterString("permissionId", null);
			String[] roleIds = this.getParameterArray("roleIds", new String[] {});
			List<String> roleIdList = Arrays.asList(roleIds);
			this.roleRelMenuService.deleteAndInsertByPermissionId(permissionId, roleIdList);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_BIND_ICON_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_BIND_ICON_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 加载菜单树
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/menuTree.json")
	public BaseResponseBody menuTree(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {

			JSONArray menuTree = this.menuService.selectMenuTreeList(null);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_TREE_SUCCESS.getMsg()), menuTree);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_TREE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 分页查询菜单列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/menuList.json")
	@RequiredParams(names = { "parentId", "pageNo", "pageSize" })
	public BaseResponseBody menuList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			MenuListRequestVO requestVO = this.getParameterBean(MenuListRequestVO.class);
			// 分页查询
			BasePage<Menu> page = new BasePage<Menu>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.menuService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存菜单信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/menuSave.json")
	@RequiredParams(names = { "name", "priority" })
	public BaseResponseBody menuSave(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求对象
			Menu menu = this.getParameterBean(Menu.class);

			if (StringUtils.isNotBlank(menu.getId())) {
				this.menuService.updateByPrimaryKeySelective(menu);
			} else {
				if (StringUtils.isNotEmpty(menu.getParentId()) && menu.getParentId().contains(",")) {
					String[] parentIds = menu.getParentId().split(",");
					for (String parentId : parentIds) {
						Menu menuAdd = new Menu();
						BeanUtils.copyProperties(menu, menuAdd);
						menuAdd.setParentId(parentId);
						Menu parentMenu = this.menuService.selectByPrimaryKey(parentId);

						this.menuService.insertSelective(menuAdd);
					}
				} else {
					this.menuService.insertSelective(menu);
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_SAVE_SUCCESS.getMsg()), true);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除菜单信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/menuDelete.json")
	@RequiredParams(names = { "ids" })
	public BaseResponseBody menuDelete(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.menuService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 菜单绑定图标
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/menuBindIcon.json")
	@RequiredParams(names = { "id", "icon" })
	public BaseResponseBody menuBindIcon(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			Menu menu = this.getParameterBean(Menu.class);

			menu.setIcon(StringEscapeUtils.unescapeHtml4(menu.getIcon())); // 图标包含&字符，XSS过滤后，需要进行反转义
			this.menuService.updateByPrimaryKeySelective(menu);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_BIND_ICON_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_BIND_ICON_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 更改显示隐藏
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateIsShow.json")
	@RequiredParams(names = { "id", "isShow" })
	public BaseResponseBody updateIsShow(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String id = this.getParameterString("id", null);
			Integer isShow = this.getParameterInteger("isShow", null);

			Menu menu = new Menu();
			menu.setId(id);
			menu.setIsShow(isShow);
			this.menuService.updateByPrimaryKeySelective(menu);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_BIND_ICON_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_BIND_ICON_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 更改显示隐藏
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateIsPassword.json")
	@RequiredParams(names = { "id", "isPassword" })
	public BaseResponseBody updateIsPassword(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String id = this.getParameterString("id", null);
			Integer isPassword = this.getParameterInteger("isPassword", null);

			Menu menu = new Menu();
			menu.setId(id);
			menu.setIsPassword(isPassword);
			this.menuService.updateByPrimaryKeySelective(menu);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_BIND_ICON_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.MENU_BIND_ICON_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

}
